package com.jy.adscm.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.bean.system.JyRole;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.system.mapper.mysql.JyRoleMapper;
import com.jy.adscm.system.service.JyRoleService;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 系统角色表 服务实现类
 * </p>
 *
 * @author yyy
 * @since 2018-08-01
 */
@Service
public class JyRoleServiceImpl extends ServiceImpl<JyRoleMapper, JyRole> implements JyRoleService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    JyRoleMapper jyRoleMapper;

    @Transactional
    @Override
    public void delRole(int roleId) throws AdscmSystemException {
        logger.info("删除角色【"+roleId+"】");

        try {
            jyRoleMapper.deleteById(roleId);

            //删除角色和用户的关联 关系
            jyRoleMapper.delRoleUser(roleId);

            //删除角色和菜单的关联关系
            jyRoleMapper.delRoleMenu(roleId);

        }catch (Exception e){
            throw new AdscmSystemException("删除角色失败："+e.getMessage());
        }


    }

    @Transactional
    @Override
    public JyRole addRole(JyRole role) throws AdscmSystemException {
        logger.info("增加角色");

        try {
            jyRoleMapper.insert(role);

        }catch (Exception e){
            throw new AdscmSystemException("增加角色失败："+e.getMessage());
        }


        return role;
    }

    @Transactional
    @Override
    public void setRoleMenus(int roleId, List<Integer> menuIds) throws AdscmSystemException {
        logger.info("绑定角色【"+roleId+"】和菜单【"+menuIds+"】的关系");

        try{
            JyRole role = jyRoleMapper.selectById(roleId);
            if (AdscmBaseUtils.getInstance().isNotEmpty(role,"id")){
                //删除角色和菜单的关联
                jyRoleMapper.delRoleMenu(roleId);

                //重新给这个角色关联菜单
                if (menuIds != null && menuIds.size()>0){
                    jyRoleMapper.setRoleMenus(roleId,menuIds);
                }

            }else {
                throw new AdscmSystemException("没有查询到角色ID【"+roleId+"】对应的角色");
            }


        }catch (Exception e){
            logger.info("绑定角色【"+roleId+"】和菜单【"+menuIds+"】的关系异常");
            throw new AdscmSystemException(e.getMessage());
        }


    }
}
